<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use think\Db;

/**
 * 商品管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Goods;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                $result = false;
                Db::startTrans();
                try {
                    // 保存商品基本信息
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 保存商品规格
                    if (!isset($params['specList']) || empty($params['specList'])) {
                        throw new \think\Exception("请至少添加一个商品规格");
                    }
                    
                    $specList = [];
                    foreach ($params['specList'] as $key => $item) {
                        if (empty($item['spec_name'])) {
                            throw new \think\Exception("第" . ($key + 1) . "个规格名称不能为空");
                        }
                        if (!isset($item['price']) || $item['price'] === '') {
                            throw new \think\Exception("第" . ($key + 1) . "个规格价格不能为空");
                        }
                        if (!isset($item['stock']) || $item['stock'] === '') {
                            throw new \think\Exception("第" . ($key + 1) . "个规格库存不能为空");
                        }
                        
                        $specList[] = [
                            'goods_id' => $this->model->id,
                            'spec_name' => $item['spec_name'],
                            'price' => $item['price'],
                            'original_price' => $item['original_price'],
                            'stock' => $item['stock']
                        ];
                    }
                    (new \app\admin\model\goods\GoodsSpec)->saveAll($specList);
                    
                    Db::commit();
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                $result = false;
                Db::startTrans();
                try {
                    if (!isset($params['specList'])){
                        $params['specList'] = [];
                    }
                    // 更新商品基本信息
                    $result = $row->allowField(true)->save($params);
                    // 获取现有规格
                    $existSpecs = \app\admin\model\goods\GoodsSpec::where('goods_id', $ids)->column('id,spec_name', 'id');
                        
                    // 找出要删除的规格ID
                    $newSpecIds = array_column($params['specList'], 'id');
                    $deleteSpecIds = array_diff(array_keys($existSpecs), $newSpecIds);
                    // 检查并删除未被引用的规格
                    if ($deleteSpecIds) {
                        foreach ($deleteSpecIds as $specId) {
                            // 检查规格是否被购物车引用
                            $cartCount = \app\common\model\Cart::where('spec_id', $specId)->count();
                            // 检查规格是否被订单引用
                            $orderCount = \app\admin\model\order\OrderItem::where('spec_id', $specId)->count();
                            
                            if ($cartCount > 0 || $orderCount > 0) {
                                throw new \think\Exception("规格[{$existSpecs[$specId]}]已被引用,无法删除");
                            }
                            
                            // 删除未被引用的规格
                            \app\admin\model\goods\GoodsSpec::where('id', $specId)->delete();
                        }
                    }
                    // 更新商品规格
                    if ($params['specList']) {
                        foreach ($params['specList'] as $item) {
                            if (!empty($item['id']) && isset($existSpecs[$item['id']])) {
                                // 更新已存在的规格
                                \app\admin\model\goods\GoodsSpec::where('id', $item['id'])
                                    ->update([
                                        'spec_name' => $item['spec_name'],
                                        'price' => $item['price'],
                                        'original_price' => $item['original_price'],
                                        'stock' => $item['stock']
                                    ]);
                            } else {
                                // 添加新规格
                                \app\admin\model\goods\GoodsSpec::create([
                                    'goods_id' => $ids,
                                    'spec_name' => $item['spec_name'],
                                    'price' => $item['price'],
                                    'original_price' => $item['original_price'],
                                    'stock' => $item['stock']
                                ]);
                            }
                        }
                    }
                    
                    Db::commit();
                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取商品规格
        $row['specList'] = \app\admin\model\goods\GoodsSpec::where('goods_id', $ids)
            ->order('id DESC')
            ->select();
            
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['category'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','title','description','cover_image','sales','status','createtime','updatetime','weigh']);
                $row->visible(['category']);
				$row->getRelation('category')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

}
